package com.example.zsf.network;

import android.content.Intent;

import com.example.zsf.ZSFApplication;
import com.example.zsf.activity.account.LoginActivity;
import com.example.zsf.base.ZSFGlobal;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;

public class TokenInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);//执行请求
        ResponseBody body = response.body();
        String json = doJson(body);
        Gson gson = new Gson();
        Map map = gson.fromJson(json, Map.class);
        if (map != null) {
            if ((double) map.get("code") == 2 && (((String) map.get("msg")).equals("登录过期"))) {
                ZSFGlobal.logout();
                Intent intent = new Intent(ZSFApplication.getInstance(), LoginActivity.class);
                startActivity(intent);
            }
        }

        return response;

    }

    private String doJson(ResponseBody responseBody) {
        long contentLength = responseBody.contentLength();
        BufferedSource source = responseBody.source();
        try {
            source.request(Long.MAX_VALUE); // Buffer the entire body.
        } catch (IOException e) {
            e.printStackTrace();
        }
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                e.printStackTrace();
            }
        }
        String result = "";
        // 拦截器，
        if (contentLength != 0) {
            result = buffer.clone().readString(charset);
        }
        return result;
    }

}
